package org.xiaojl.common.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xiaojl.common.Constants;
import org.xiaojl.common.SessionUser;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.config.shiro.captcha.DreamCaptcha;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

@Controller
public class LoginController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	@Autowired
    private DreamCaptcha dreamCaptcha;
	
	/**
     * GET 登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return "redirect:framework/index";
        }
        /**
         * logout可以安全正确退出,session也可以删除，授权信息，认证信息也会被清除
         */
        SecurityUtils.getSubject().logout();
        //是否需要登录验证码
        model.addAttribute("captchaOpen", Constants.CAPTCHA_OPEN);
        return "login";
    }

    /**
     * POST 登录 shiro 写法
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody Object loginPost(String username, String password, String captcha) {
        log.info("POST请求登录");
        if (ToolUtil.isEmpty(username)) {
            return operateError("用户名不能为空");
        }
        if (ToolUtil.isEmpty(password)) {
            return operateError("密码不能为空");
        }
        if(Constants.CAPTCHA_OPEN){//判断是否开启了登录验证码功能
        	if (ToolUtil.isEmpty(captcha)) {
            	return operateError("验证码不能为空");
            }else{
            	if (!dreamCaptcha.validate(request, response, captcha)) {
            		return operateError("验证码不正确");
                }
            }
        }
        
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        // 默认设置为记住密码，你可以自己在表单中加一个参数来控制
        token.setRememberMe(true);
        try {
            user.login(token);
            
            //手动添加到session中
            SessionUser su = (SessionUser)SecurityUtils.getSubject().getPrincipal();
            session.setAttribute(Constants.SESSION_USER, su);
            
        } catch (UnknownAccountException e) {
            log.error("账号不存在！", e);
            return operateError("账号或者密码错误");
        } catch (DisabledAccountException e) {
            log.error("账号未启用！", e);
            return operateError("账号被禁用了");
        } catch (IncorrectCredentialsException e) {
            log.error("密码错误！", e);
            return operateError("账号或者密码错误");
        } catch (RuntimeException e) {
            log.error("未知错误,请联系管理员！", e);
            return operateError();
        }
        return operateSuccess("登录成功");
    }

    /**
     * 未授权
     */
    @RequestMapping(value = "/unauth")
    public String unauth() {
        if (SecurityUtils.getSubject().isAuthenticated() == false) {
            return "redirect:/login";
        }
        return "noAuth";
    }
	
    /**
     * 退出
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public Object logout() {
        try {
        	SessionUser user = WebUtil.getSessionUser();
            log.debug(user.getRealName()+"("+user.getLoginName()+")"+"退出系统");
        	//入库
            
            //session失效
            session.removeAttribute(Constants.SESSION_USER);
			
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
			
		} catch (Exception e) {
			log.error("未知错误", e);
			return operateError();
		}
        return operateSuccess("成功退出系统");
    }
}
